#!/usr/bin/env python

# Copyright 2012 Google Inc. All Rights Reserved.

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#     http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License."

"""Helper for parsing stacktraces generated by V8 and JSC."""

import re


class Stack(object):
  """Represents a stack trace as generated by WebKit."""

  # The member vm will be set to one of these constants to indiciate what
  # JavaScript vm generated the stack trace.
  V8 = 'v8'
  JSC = 'jsc'
  UNKNOWN = 'unknown'

  def __init__(self, stack_as_string):
    frames = stack_as_string.split('\n')
    if frames[0] == 'Error':
      self.vm = self.V8
      self._regex = re.compile(r'\s+at\s+([^(]+?)( \(.*)?$')
      self.frames = [self._ParseFrame(f) for f in frames[1:]]
    elif frames[0] == '--> Stack trace:':
      self.vm = self.JSC
      self._regex = re.compile(r'\s+\d+\s+([^@]*)(@.*)?$')
      self.frames = [self._ParseFrame(f) for f in frames[1:]]
    else:
      self.vm = self.UNKNOWN
      self.frames = frames

  def _ParseFrame(self, frame):
    """Parses a frame.

    Args:
        frame: A string representing a call stack frame

    Returns:
        A string representing the function name in the call stack or "*" if
        the frame could not be parsed
    """
    match = self._regex.match(frame)
    if not match or not match.group(1):
      return '*'
    return match.group(1)
